package com.ruoyi.web.controller.activemq;

import org.apache.activemq.ScheduledMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.jms.*;

/**
 * @ClassName ProducerController
 * @Description TODO
 * @Author luguanqing
 * @Date 2021/6/22 10:15
 * @Version 1.0
 */
@RestController
public class ProducerController {

    private final ActiveMQHandler handler;

    @Autowired
    public ProducerController(ActiveMQHandler handler) {
        this.handler = handler;
    }

    @Autowired
    private JmsMessagingTemplate jmsMessagingTemplate;

    @Autowired
    private Queue queue;

    @Autowired
    private Topic topic;

    @PostMapping("/queue/test")
    public String sendQueue(@RequestBody String str){
        this.sendMessage(this.queue, str);
        return "success";
    }

    @PostMapping("/topic/test")
    public String sendTopic(@RequestBody String str){
        this.sendMessage(this.topic, str);
        return "success";
    }

    //发送消息，destination发送到队列，message待发送消息
    private void sendMessage(Destination destination, final String message){
        jmsMessagingTemplate.convertAndSend(destination, message);
    }

    /**
     * 延迟消息
     * @return
     */
    @RequestMapping("/delaySend")
    public String delaySend(){
        // 构建一个消息, 名称是 queue01
        for (int i = 0; i < 10; i++) {
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            String message = "我是延迟消息内容, " + i;
            handler.delaySend("delaySend01",message,10);
        }
        return "success";
    }

}
